package com.wkq.util.socket

import WebSocketClientImpl
import android.util.Log
import androidx.lifecycle.LifecycleOwner

class WebSocketManager private constructor() {

    @Volatile
    private var client: WebSocketClientImpl? = null

    private val defaultConfig = WebSocketConfig(
        headers = emptyMap(), connectTimeout = 5000, pingTime = 10000, maxReconnectNum = -1,
        reconnectMaxDelay = 10000
    )

    /**
     * 初始化并连接 WebSocket
     */
    fun init(
        url: String, lifecycleOwner: LifecycleOwner?, listener: SocketListener?,
        config: WebSocketConfig = defaultConfig
    ) {
        if (client == null) {
            synchronized(this) {
                if (client == null) {
                    client = WebSocketClientImpl(url, config, listener, lifecycleOwner).apply {
                        enableReconnect()
                        connect()
                    }
                }
            }
        }
    }

    fun send(message: String): Boolean {
        Log.e("Socket:发送消息:", message)
        return client?.send(message) ?: false
    }


    fun connect() {
        client?.connect()
    }

    fun disconnect() {
        client?.disconnect()
    }

    fun release() {
        synchronized(this) {
            client?.release()
            client = null
        }
    }

    companion object {
        @Volatile
        private var instance: WebSocketManager? = null

        fun getInstance(): WebSocketManager {
            if (instance == null) {
                synchronized(WebSocketManager::class) {
                    if (instance == null) {
                        instance = WebSocketManager()
                    }
                }
            }
            return instance!!
        }
    }
}
